<script lang="ts" setup>
import { ref, watch, reactive } from "vue"
import { usePagination } from "@/hooks/usePagination"
import { type IGetOrderData } from "@/api/order/types/order"
import { ElTable } from "element-plus"
import { getH5OrderDataApi, updateAndPushH5OrderDataApi, downLoadOrderH5Table } from "@/api/orderH5Ys"
import { uploadCidImageList } from "@/api/order"

import { type FormInstance, type FormRules, ElMessage } from "element-plus"

import { Search, Refresh, Download, RefreshRight } from "@element-plus/icons-vue"
import { useUserStore } from "@/store/modules/user"
import { useComboStore } from "@/store/modules/combo"
import { formatDateTime } from "@/utils"

import { checkPhoneNumber, checkID, isAddressDetailed } from "@/utils/validate"
defineOptions({
  name: "XcxYsOrder"
})
const formRef = ref<FormInstance | null>(null)
const seeState = ref("")

const comboStore = useComboStore()
const formData = reactive<any>({})
const searchData = reactive<any>({})
const searchFormRef = ref<FormInstance | null>(null)
const userStore = useUserStore()

const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
const tableData = ref<IGetOrderData[]>([])
const comboList = ref<any>([])
const loading = ref<boolean>(false)
// const currentId = ref<any>(undefined)
const dialogVisible = ref<boolean>(false)
const fileList0 = ref<any>([]) //身份证正面
const fileList1 = ref<any>([]) //身份证反面
const fileList2 = ref<any>([]) //人像

const formRules: FormRules = reactive({
  orderId: [{ required: true, trigger: "blur", message: "请输入订单名称" }],
  ys_card_name: [{ required: true, trigger: "blur", message: "请填写姓名" }],
  ys_package_id: [{ required: true, trigger: "blur", message: "请选择系统套餐" }],
  ys_card_id: [{ required: true, validator: checkID, trigger: "blur" }],
  ys_phone: [{ required: true, validator: checkPhoneNumber, trigger: "blur" }],
  ys_address: [{ required: true, validator: isAddressDetailed, trigger: "blur" }]
})
searchData.searchDate = ref("")
const getTableData = () => {
  if (!searchData.searchDate) {
    searchData.searchDate = []
  }
  loading.value = true
  getH5OrderDataApi({
    page: paginationData.currentPage,
    size: paginationData.pageSize,
    ys_card_name: searchData.ys_card_name,
    ys_card_id: searchData.ys_card_id,
    ys_phone: searchData.ys_phone,
    // ys_team_id: userStore.usernameID,
    ys_state: searchData.ys_state,
    ys_up_id: searchData.ys_up_id,
    ys_package_id: searchData.ys_package_id,
    start: new Date(searchData?.searchDate[0]).getTime() || "",
    end: new Date(searchData?.searchDate[1]).getTime() || ""
  })
    .then((res: any) => {
      paginationData.total = res.data.total
      tableData.value = res.data.list
    })
    .catch(() => {
      tableData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}

const handleSearch = () => {
  if (paginationData.currentPage === 1) {
    getTableData()
  }
  paginationData.currentPage = 1
}
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  if (paginationData.currentPage === 1) {
    getTableData()
  }
  paginationData.currentPage = 1
}

//row 数据通用
const rowData = (row: any) => {
  formData.cardBack = row.cardBack
  formData.cardFront = row.cardFront
  formData.ys_address = row.ys_address
  formData.ys_card_id = row.ys_card_id
  formData.ys_card_name = row.ys_card_name
  formData.ys_city = row.ys_city
  formData.ys_date = row.ys_date
  formData.ys_district = row.ys_district
  formData.ys_id = row.ys_id
  formData.ys_note = row.ys_note
  formData.ys_package_name = row.ys_package_name
  formData.ys_phone = row.ys_phone
  formData.ys_province = row.ys_province
  formData.ys_state = row.ys_state
  formData.ys_team_id = row.ys_team_id
  formData.ys_up_id = row.ys_up_id
  formData.photo = row.photo
  formData.ys_order_id = row.ys_order_id // 外部订单ID
  formData.system_package_name = row.system_package_name
  if (row.ys_state === "已提交") {
    formData.ys_package_id = row.ys_package_id
  } else {
    formData.ys_package_id = ""
  }
  if (row.cardFront) {
    fileList0.value = row.cardFront?.split(",").map((item: any) => {
      return {
        url: `http://fansitexitong.cn/image/${item}`
      }
    })
  } else {
    fileList0.value = []
  }

  // console.log(fileList0.value, 999)

  if (row.cardBack) {
    fileList1.value = row.cardBack?.split(",").map((item: any) => {
      return {
        url: `http://fansitexitong.cn/image/${item}`
      }
    })
  } else {
    fileList1.value = []
  }
  if (row.photo) {
    fileList2.value = row.photo?.split(",").map((item: any) => {
      return {
        url: `http://fansitexitong.cn/image/${item}`
      }
    })
  } else {
    fileList2.value = []
  }

  dialogVisible.value = true
}

//查看详情
const handleSeeInfo = (row: any) => {
  seeState.value = "see"
  rowData(row)
}
//修改
const handleUpdate = (row: any) => {
  seeState.value = "update"
  rowData(row)
}
/** 图片改变 */
const handleChageImg = (file: any, resfileList: any) => {
  const size = ref(2)
  const fileSizeFlag = file.size / 1024 / 1024 < size.value
  if (!fileSizeFlag) {
    ElMessage.error(`请上传不大于${size.value}M的图片!`)
    fileList0.value = []
  } else {
    fileList0.value = resfileList
  }
}
const handleChageImg1 = (file: any, resfileList: any) => {
  const size = ref(2)
  const fileSizeFlag = file.size / 1024 / 1024 < size.value
  if (!fileSizeFlag) {
    ElMessage.error(`请上传不大于${size.value}M的图片!`)
    fileList1.value = []
  } else {
    fileList1.value = resfileList
  }
}
const handleChageImg2 = (file: any, resfileList: any) => {
  const size = ref(2)
  const fileSizeFlag = file.size / 1024 / 1024 < size.value
  if (!fileSizeFlag) {
    ElMessage.error(`请上传不大于${size.value}M的图片!`)
    fileList2.value = []
  } else {
    fileList2.value = resfileList
  }
}
// 移除图片
const handleRemove = (file: any) => {
  const list = fileList0.value
  for (const i in list) {
    if (list[i].uid === file.uid) {
      list.splice(i, 1)
    }
  }
  fileList0.value = list
}
// 移除图片
const handleRemove1 = (file: any) => {
  const list = fileList1.value
  for (const i in list) {
    if (list[i].uid === file.uid) {
      list.splice(i, 1)
    }
  }
  fileList1.value = list
}
// 移除图片
const handleRemove2 = (file: any) => {
  const list = fileList2.value
  for (const i in list) {
    if (list[i].uid === file.uid) {
      list.splice(i, 1)
    }
  }
  fileList2.value = list
}

// 预览图片
const dialogImageUrl = ref("") /**预览url  */
const dialogVisible1 = ref(false) /**预览弹窗 */
const handlePictureCardPreview = (file: any) => {
  dialogImageUrl.value = file.url
  dialogVisible1.value = true
}
//修改信息重新提交
const uploadFuc = async () => {
  loading.value = true
  // if (fileList0.value.length === 0 || fileList1.value.length === 0 || fileList2.value.length === 0) {
  //   ElMessage.error("请上传相关照片")
  //   loading.value = false
  //   return
  // }
  const fileData = new FormData()
  const fileData1 = new FormData()
  const fileData2 = new FormData()
  fileList0.value.forEach((file: any) => {
    fileData.append("file", file.raw)
    fileData.append("name", formData.cardName)
  })
  fileList1.value.forEach((file: any) => {
    fileData1.append("file", file.raw)
    fileData1.append("name", formData.cardName)
  })
  fileList2.value.forEach((file: any) => {
    fileData2.append("file", file.raw)
    fileData2.append("name", formData.cardName)
  })
  if (fileList0.value.length && fileList0.value[0].status === "ready") {
    await uploadCidImageList(fileData).then((res: any) => {
      if (res.code == 200) {
        formData.cardFront = res.data.split("/image/")[1]
        fileList0.value = []
      }
    })
  }
  if (fileList1.value.length && fileList1.value[0].status === "ready") {
    await uploadCidImageList(fileData1).then((res: any) => {
      if (res.code == 200) {
        formData.cardBack = res.data.split("/image/")[1]
        fileList1.value = []
      }
    })
  }
  if (fileList2.value.length && fileList2.value[0].status === "ready") {
    await uploadCidImageList(fileData2).then((res: any) => {
      if (res.code == 200) {
        formData.photo = res.data.split("/image/")[1]
        fileList2.value = []
      }
    })
  }
  await updateAndPushH5OrderDataApi(formData)
    .then((res: any) => {
      if (res.code == 200) {
        dialogVisible.value = false
        getTableData()
      }
    })
    .finally(() => {
      loading.value = false
    })
}

const handleCreate = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      uploadFuc()
    } else {
      return false
    }
  })
}

const resetForm = () => {
  fileList0.value = []
  fileList1.value = []
  fileList2.value = []
  // 清空reactive对象里面的key值
  Object.keys(formData).map((key) => {
    delete formData[key]
  })
}

/**日期相关 */
import { shortcuts } from "@/utils/dateSet"
const defaultTime1: [Date, Date] = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)]

/**END */
/**加密 */
const toHideString = (val: any, len: any) => {
  if (val) {
    return `${val.substring(0, len)}******${val.substring(val.length - len)}`
  }
  if (val && val.length == 2) {
    return `${val.substring(0, len)}******${val.substring(val.length)}`
  }
}

/**刷新 */
const handleRefresh = () => {
  getTableData()
}

/**下载 */
const downLoad = () => {
  downLoadOrderH5Table({
    ys_card_name: searchData.ys_card_name,
    ys_card_id: searchData.ys_card_id,
    ys_phone: searchData.ys_phone,
    ys_up_id: searchData.ys_up_id,
    ys_package_id: searchData.ys_package_id,
    ys_state: searchData.ys_state,
    ys_team_id: userStore.usernameID,
    start: new Date(searchData?.searchDate[0]).getTime() || "",
    end: new Date(searchData?.searchDate[1]).getTime() || ""
  }).then((res: any) => {
    // console.log(res)
    const blob = new Blob([res.data], {
      type: "application/xlsx;charset=utf-8"
    })
    // console.log(res)
    const downloadElement = document.createElement("a")
    const href = window.URL.createObjectURL(blob)
    downloadElement.href = href
    downloadElement.download = "云尚订单.xlsx"
    document.body.appendChild(downloadElement)
    downloadElement.click()
    window.URL.revokeObjectURL(href)
  })
}

/** 监听分页参数的变化 */
const comboList1 = ref<any>([])
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })
comboStore.getComoboFn()
watch(
  [() => comboStore.comboListStore],
  (newValue) => {
    comboList.value = newValue.flat().filter((item) => item.state === "true")
    comboList1.value = newValue.flat()
  },
  {
    immediate: true
  }
)

/**E N D */
</script>

<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="ys_card_name" label="姓名">
          <el-input v-model.trim="searchData.ys_card_name" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="ys_card_id" label="身份证">
          <el-input v-model.trim="searchData.ys_card_id" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="ys_phone" label="收件电话">
          <el-input v-model.trim="searchData.ys_phone" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="ys_up_id" label="推广人ID">
          <el-input v-model.trim="searchData.ys_up_id" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="ys_package_id" label="系统套餐">
          <el-select v-model="searchData.ys_package_id" clearable filterable placeholder="请选套餐" style="width: 100%">
            <el-option v-for="item in comboList1" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item prop="ys_state" label="提交状态">
          <el-select v-model="searchData.ys_state" clearable filterable placeholder="请选择" style="width: 100%">
            <el-option :key="1" label="已提交" value="已提交" />
            <el-option :key="2" label="未提交" value="未提交" />
          </el-select>
        </el-form-item>

        <el-form-item prop="searchDate" label="订单日期">
          <el-date-picker
            v-model="searchData.searchDate"
            type="datetimerange"
            unlink-panels
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :shortcuts="shortcuts"
            :default-time="defaultTime1"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card>
      <div class="toolbar-wrapper">
        <div />
        <div>
          <el-tooltip content="下载">
            <el-button type="primary" :icon="Download" circle @click="downLoad" />
          </el-tooltip>
          <el-tooltip content="刷新表格">
            <el-button type="primary" :icon="RefreshRight" circle @click="handleRefresh" />
          </el-tooltip>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table :data="tableData">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column prop="ys_id" label="ID" align="center" />
          <el-table-column prop="ys_order_id" label="订单ID" align="center" />
          <el-table-column prop="ys_date" label="创建时间" align="center">
            <template #default="scope"> {{ formatDateTime(scope.row.ys_date) }} </template>
          </el-table-column>
          <el-table-column prop="ys_package_name" label="套餐" align="center" />
          <el-table-column prop="system_package_name" label="对应系统套餐" align="center" width="280" />
          <el-table-column prop="ys_card_name" label="身份证姓名" align="center">
            <template #default="scope">
              {{ toHideString(scope.row.ys_card_name, 1) }}
            </template>
          </el-table-column>
          <el-table-column prop="ys_card_id" label="身份证号" align="center">
            <template #default="scope">
              {{ toHideString(scope.row.ys_card_id, 6) }}
            </template>
          </el-table-column>
          <el-table-column prop="ys_phone" label="收货电话" align="center" />
          <el-table-column prop="ys_handle_mobile" label="入网号" align="center" />
          <el-table-column prop="ys_up_id" label="推广人ID" align="center" />
          <el-table-column prop="ys_up_name" label="推广人账户" align="center" width="180" />
          <el-table-column prop="ys_order_state" label="订单状态" align="center">
            <template #default="scope">
              <div
                :class="{
                  doing: scope.row.ys_order_state?.code <= 200 && scope.row.ys_order_state?.code > 199,
                  success: scope.row.ys_order_state?.code >= 100 && scope.row.ys_order_state?.code < 200,
                  error: scope.row.ys_order_state?.code >= 400,
                  again: scope.row.ys_order_state?.code < 0
                }"
              >
                {{ scope.row.ys_order_state?.state }}
                <div class="text-ellipsis" v-if="scope.row.ys_result" style="font-size: 12px">
                  <el-tooltip placement="top">
                    <template #content> {{ scope.row.ys_result }} </template>
                    <span style="cursor: pointer">({{ scope.row.ys_result }})</span>
                  </el-tooltip>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="提交状态" align="center">
            <template #default="scope">
              <span v-if="scope.row.ys_state === '已提交'" style="color: #67c23a">已提交</span>
              <span v-if="scope.row.ys_state.indexOf('未提交') != -1" style="color: #f56c6c">{{
                scope.row.ys_state
              }}</span>
            </template>
          </el-table-column>
          <el-table-column label="收货地址" align="center" show-overflow-tooltip>
            <template #default="scope">
              {{ scope.row.ys_address.split(" ")[0] }}
              {{ scope.row.ys_address.split(" ")[1] }}
              {{ scope.row.ys_address.split(" ")[2] }}
              {{ toHideString(scope.row.ys_address.split(" ")[3], 0) }}
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" align="center">
            <template #default="scope">
              <el-button type="primary" text bg size="small" @click="handleSeeInfo(scope.row)">查看详情</el-button
              ><br />
              <el-button
                :disabled="scope.row.ys_state.indexOf('未提交') == -1"
                type="primary"
                text
                bg
                size="small"
                @click="handleUpdate(scope.row)"
                >修改重提</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <el-dialog v-model="dialogVisible" :title="seeState === 'see' ? '查看详情' : '修改'" @close="resetForm" width="80%">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" label-position="left">
        <!-- <el-form-item prop="orderId" label="订单外部ID">
          <el-input v-model="formData.orderId" placeholder="请输入" disabled />
        </el-form-item> -->
        <el-form-item prop="ys_card_name" label="姓名">
          <el-input v-model="formData.ys_card_name" placeholder="请输入" :disabled="seeState === 'see'" />
        </el-form-item>
        <el-form-item prop="ys_card_id" label="身份证号">
          <el-input v-model="formData.ys_card_id" placeholder="请输入" :disabled="seeState === 'see'" />
        </el-form-item>
        <el-form-item prop="ys_phone" label="收货电话">
          <el-input v-model="formData.ys_phone" placeholder="请输入" :disabled="seeState === 'see'" />
        </el-form-item>
        <el-form-item prop="ys_address" label="收货地址">
          <el-input v-model="formData.ys_address" placeholder="请输入" :disabled="seeState === 'see'" />
        </el-form-item>
        <el-form-item prop="ys_package_name" label="套餐">
          <el-input v-model="formData.ys_package_name" placeholder="请输入" disabled />
        </el-form-item>
        <el-form-item prop="ys_package_id" label="系统套餐">
          <el-select
            v-model="formData.ys_package_id"
            :disabled="seeState === 'see'"
            clearable
            filterable
            placeholder="请选套餐"
            style="width: 100%"
          >
            <el-option v-for="item in comboList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item prop="ys_note" label="备注">
          <el-input v-model="formData.ys_note" placeholder="请输入" type="textarea" :disabled="seeState === 'see'" />
        </el-form-item>
        <el-form-item v-if="formData.cardFront" prop="cardFront" label="身份证正面照">
          <el-upload
            :auto-upload="false"
            :file-list="fileList0"
            :show-file-list="true"
            list-type="picture-card"
            :limit="1"
            accept="image/*"
            :on-change="handleChageImg"
            :disabled="fileList0.length !== 0"
          >
            <el-icon><Plus /></el-icon>
            <template #file="{ file }">
              <div>
                <img class="el-upload-list__item-thumbnail" :src="file.url" />
                <span class="el-upload-list__item-actions">
                  <span class="el-upload-list__item-delete" @click="handleRemove(file)" v-if="seeState !== 'see'">
                    <el-icon>
                      <Delete />
                    </el-icon>
                  </span>
                  <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                    <el-icon>
                      <zoom-in />
                    </el-icon>
                  </span>
                </span>
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item v-if="formData.cardBack" prop="cardBack" label="身份证反面照">
          <el-upload
            :auto-upload="false"
            :file-list="fileList1"
            :show-file-list="true"
            list-type="picture-card"
            :limit="1"
            accept="image/*"
            :on-change="handleChageImg1"
            :disabled="fileList1.length !== 0"
          >
            <el-icon><Plus /></el-icon>
            <template #file="{ file }">
              <div>
                <img class="el-upload-list__item-thumbnail" :src="file.url" />
                <span class="el-upload-list__item-actions">
                  <span class="el-upload-list__item-delete" @click="handleRemove1(file)" v-if="seeState !== 'see'">
                    <el-icon>
                      <Delete />
                    </el-icon>
                  </span>
                  <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                    <el-icon>
                      <zoom-in />
                    </el-icon>
                  </span>
                </span>
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item v-if="formData.photo" prop="photo" label="人像照片">
          <el-upload
            :auto-upload="false"
            :file-list="fileList2"
            :show-file-list="true"
            list-type="picture-card"
            :limit="1"
            accept="image/*"
            :on-change="handleChageImg2"
            :disabled="fileList2.length !== 0"
          >
            <el-icon><Plus /></el-icon>
            <template #file="{ file }">
              <div>
                <img class="el-upload-list__item-thumbnail" :src="file.url" />
                <span class="el-upload-list__item-actions">
                  <span class="el-upload-list__item-delete" @click="handleRemove2(file)" v-if="seeState !== 'see'">
                    <el-icon>
                      <Delete />
                    </el-icon>
                  </span>
                  <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                    <el-icon>
                      <zoom-in />
                    </el-icon>
                  </span>
                </span>
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreate">确认</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="dialogVisible1">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
:deep(.el-upload-list__item .el-icon--close-tip) {
  top: 20px;
  left: 10px;
  right: 0;
}
.doing {
  color: #b88230;
}
.error {
  color: red;
}
.success {
  color: #67c23a;
}
.again {
  color: #c45656;
}
:deep(.el-popper) {
  max-width: 50% !important;
}
.text-ellipsis {
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  -webkit-line-clamp: 3;
  display: -webkit-box;
  -webkit-box-orient: vertical;
}
</style>
<style>
.el-popper.is-customized {
  /* Set padding to ensure the height is 32px */
  padding: 6px 12px;
  background: linear-gradient(90deg, rgb(159, 229, 151), rgb(204, 229, 129));
}

.el-popper.is-customized .el-popper__arrow::before {
  background: linear-gradient(45deg, #b2e68d, #bce689);
  right: 0;
}
</style>
